<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <el-button type="primary" @click="addRoleDialogVisible = true"
        >添加用户</el-button
      >
      <!-- 角色列表区域 -->
      <el-table :data="roleList" border stripe>
        <!-- 下拉列表 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <!-- {{ scope.row }} -->
            <el-row
              :class="['bdbottom', i1 === 0 ? 'bdtop' : '', 'elCenter']"
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag
                  closable
                  @close="deleteRoleInfoById(scope.row, item1.id)"
                  >{{ item1.authName }}</el-tag
                >
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级和三级权限 -->
              <el-col :span="19">
                <el-row
                  :class="[i2 === 0 ? '' : 'bdtop', 'elCenter']"
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                >
                  <!-- 二级权限 -->
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="deleteRoleInfoById(scope.row, item2.id)"
                      >{{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级权限 -->
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      :class="[i3 === 0 ? '' : 'bdtop']"
                      v-for="(item3, i3) in item2.children"
                      :key="item3.id"
                      closable
                      @close="deleteRoleInfoById(scope.row, item3.id)"
                      >{{ item3.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 角色列表数据区域 -->
        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <!-- 角色按钮操作 -->
          <template slot-scope="scope">
            <!-- {{ scope.row }} -->
            <!-- 编辑角色按钮 -->
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="editRoleInfoById(scope.row)"
              >编辑</el-button
            >
            <!-- 删除角色按钮 -->
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="deleteRoleInfo(scope.row.id)"
              >删除</el-button
            >
            <!-- 给角色分配权限按钮 -->
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-setting"
              @click="showRoleRightsDialog(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 添加用户对话框区域 -->
      <el-dialog
        title="添加角色"
        :visible.sync="addRoleDialogVisible"
        width="50%"
        @close="addRoleDialogColsed"
      >
        <el-form
          :model="addRoleForm"
          :rules="addRoleFormRules"
          ref="addRoleFormRef"
          label-width="100px"
        >
          <!-- 添加的用户名 -->
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="addRoleForm.roleName"></el-input>
          </el-form-item>
          <!-- 添加的角色描述 -->
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="addRoleForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer">
          <el-button @click="addRoleDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addRole">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 编辑角色对话框区域 -->
      <el-dialog
        title="修改角色"
        :visible.sync="editRoleDialogVisible"
        width="50%"
        @close="editRoleDialogColsed"
      >
        <el-form
          :model="editRoleList"
          :rules="editRoleRules"
          ref="editRoleRef"
          label-width="100px"
        >
          <!-- 修改用户名 -->
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="editRoleList.roleName"></el-input>
          </el-form-item>
          <!-- 修改角色描述 -->
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="editRoleList.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer">
          <el-button @click="editRoleDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveSetRoleInfo">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 分配权限对话框区域 -->
      <el-dialog
        title="分配权限"
        :visible.sync="roleRightsDialogVisible"
        width="50%"
        @close="roleRightsDialogColsed"
      >
        <el-tree
          :data="rightList"
          :props="treeProps"
          show-checkbox
          :default-expand-all="true"
          node-key="id"
          :default-checked-keys="defKeys"
          ref="treeRef"
        >
        </el-tree>
        <span slot="footer">
          <el-button @click="roleRightsDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="allotRights">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'Roles',
  data() {
    return {
      // 获取角色列表
      roleList: [],
      // 隐藏编辑角色对话框
      editRoleDialogVisible: false,
      // 编辑角色的用户数据列表
      editRoleList: [],
      // 编辑角色的数据校验规则
      editRoleRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 2, max: 6, message: '长度在 2 到 6 个字符', trigger: 'blur' },
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          {
            min: 2,
            max: 20,
            message: '长度在 2 到 20 个字符',
            trigger: 'blur',
          },
        ],
      },
      // 隐藏角色权限对话框
      roleRightsDialogVisible: false,
      // 获取所有权限信息列表
      rightList: [],
      treeProps: {
        label: 'authName',
        children: 'children',
      },
      // 默认选中的节点Id值数组
      defKeys: [],
      // 当前即将分配权限的角色 id
      roleId: '',
      // 隐藏添加用户对话框
      addRoleDialogVisible: false,
      // 添加角色用户数据
      addRoleForm: {
        roleName: '',
        roleDesc: '',
      },
      // 添加角色的校验规则
      addRoleFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 2, max: 6, message: '长度在 2 到 6 个字符', trigger: 'blur' },
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          {
            min: 2,
            max: 20,
            message: '长度在 2 到 20 个字符',
            trigger: 'blur',
          },
        ],
      },
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    // 获取角色列表数据
    async getRoleList() {
      const { data: res } = await this.$http.get('roles')
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败')
      }
      this.roleList = res.data
    },
    // 删除角色的单个权限事件
    async deleteRoleInfoById(Role, RightId) {
      const { data: res } = await this.$http.delete(
        `roles/${Role.id}/rights/${RightId}/`
      )
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('删除失败')
      }
      this.$message.success('删除成功')
      // 用这种方式更新数据，删除了某个权限，会收回下拉框
      // this.getRoleList()
      // 使用这种方式不会
      // console.log(this.roleList)
      Role.children = res.data
    },
    // 获取编辑角色数据事件
    async editRoleInfoById(role) {
      const { data: res } = await this.$http.get('roles/' + role.id)
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('获取失败')
      }
      this.editRoleList = res.data
      // console.log(this.editRoleList)

      // 显示编辑角色对话框
      this.editRoleDialogVisible = true
    },
    // 监听关闭编辑角色对话框
    editRoleDialogColsed() {
      this.$refs.editRoleRef.resetFields()
    },
    // 监听修改的用户确定事件
    saveSetRoleInfo() {
      this.$refs.editRoleRef.validate(async (valid) => {
        // console.log(valid)
        if (!valid) return
        const { data: res } = await this.$http.put(
          'roles/' + this.editRoleList.roleId,
          {
            roleName: this.editRoleList.roleName,
            roleDesc: this.editRoleList.roleDesc,
          }
        )
        // console.log(res)
        if (res.meta.status !== 200) {
          return this.$message.error('修改失败')
        }
        this.$message.success('修改成功')
        this.editRoleDialogVisible = false
        this.getRoleList()
      })
    },
    // 监听删除用户事件
    async deleteRoleInfo(id) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该角色, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)
      // console.log(confirmResult)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      // console.log(role)
      const { data: res } = await this.$http.delete('roles/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('删除失败')
      }
      this.$message.success('删除成功')
      this.getRoleList()
    },
    // 分配权限按钮事件
    async showRoleRightsDialog(role) {
      this.roleId = role
      // 获取所有权限列表
      const { data: res } = await this.$http.get('rights/tree')
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('获取失败')
      }
      this.rightList = res.data
      // 调用 this.getLeafKeys 获取到选中的 id
      this.getLeafKeys(role, this.defKeys)

      // 显示角色权限对话框
      this.roleRightsDialogVisible = true
    },
    // 通过递归的形式，获取角色下所有三级权限的id，并保持到 derkeys 数组中
    getLeafKeys(node, arr) {
      // 如果当前 node 节点不包含 children 属性，则是三级节点
      if (!node.children) {
        return arr.push(node.id)
      }
      // 如果含有 children 则进行递归遍历，知道没有 children 属性
      node.children.forEach((item) => this.getLeafKeys(item, arr))
    },
    // 监听关闭角色分配权限对话框事件
    roleRightsDialogColsed() {
      this.defKeys = []
    },
    // 监听角色分配权限的确定事件
    async allotRights() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys(),
      ]
      // console.log(keys)
      const idStr = keys.join(',')
      // console.log(idStr)
      const { data: res } = await this.$http.post(
        `roles/${this.roleId.id}/rights`,
        { rids: idStr }
      )
      // console.log(res, this.roleId.id)
      if (res.meta.status !== 200) {
        return this.$message.error('分配权限失败')
      }
      this.$message.success('分配权限成功')
      this.getRoleList()
      this.roleRightsDialogVisible = false
    },
    // 监听添加角色的确定事件
    addRole() {
      this.$refs.addRoleFormRef.validate(async (valida) => {
        if (!valida) return
        const { data: res } = await this.$http.post('roles', this.addRoleForm)
        if (res.meta.status !== 201) {
          return this.$message.error('添加失败')
        }
        this.$message.success('添加成功')
        this.getRoleList()
        this.addRoleDialogVisible = false
      })
    },
    // 监听添加角色对话框的关闭事件
    addRoleDialogColsed() {
      this.$refs.addRoleFormRef.resetFields()
    },
  },
}
</script>

<style>
.el-tag {
  margin: 7px;
}
/* 顶部边框线 */
.bdtop {
  border-top: 1px solid #eee;
}
/* 底部边框线 */
.bdbottom {
  border-bottom: 1px solid #eee;
}
/* 弹性布局，居中 */
.elCenter {
  display: flex;
  align-items: center;
}
</style>